import React, { useState, useEffect, useRef } from "react";
import type { FormProps } from "antd";
import { Button, Modal, Checkbox, Form, Input, message } from "antd";
import { addArtData, getArtDataById } from "@/api/artCate/index";

const Comp: React.FC = ({ SonObj }) => {
  // const formRef = useRef<any>();
  const [form] = Form.useForm();
  // 根据Id获取数据
  const getDataById = async () => {
    try {
      const res = await getArtDataById({ id: SonObj.id });
      if (res.code === 200) {
        // console.log("res", res);
        form.setFieldsValue({
          name: res.data.name,
          alias: res.data.alias,
        });
      }
    } catch (error) {}
  };

  useEffect(() => {
    if (SonObj.modal) {
      setOpen(SonObj.modal);
      form.setFieldsValue({
        name: "",
        alias: "",
      });
    }
  }, [SonObj.modal]);
  useEffect(() => {
    if (SonObj.id) getDataById();
  }, [SonObj.id]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const showModal = () => {
    setOpen(true);
  };
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      console.log("values", values);
      const res = await addArtData(values);
      if (res.code === 200) {
        message.success(res.msg);
        setOpen(false);
        SonObj.modalClose();
        SonObj.getList();
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      console.log("error", error);
    }
  };
  type FieldType = {
    name: string;
    alias: string;
  };
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
  };
  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  const handleCancel = () => {
    // console.log("Clicked cancel button");
    setOpen(false);
    SonObj.modalClose();
  };

  return (
    <>
      <Modal
        open={open}
        title={SonObj.title}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
            确定
          </Button>,
        ]}
      >
        <Form
          // ref={formRef}
          form={form}
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 14 }}
          style={{ maxWidth: 600 }}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="name" name="name" rules={[{ required: true, message: "请输入分类名称" }]}>
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="alias" name="alias" rules={[{ required: true, message: "请输入分类别名" }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Comp;
